package com.feedgraph;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;

import com.feedgraph.FeedManager.BasicFeed;
import com.feedgraph.FeedManager.Feed;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.net.Uri;
import android.util.Log;

public class AsyncFeedLoader extends AsyncTaskLoader <BasicFeed> {

	private static class Subscription {
		public Uri uri;
		public boolean ignoreOld;

		public Subscription (Uri uri, boolean ignoreOld) {
			this.uri = uri;
			this.ignoreOld = ignoreOld;
		}
	}

	protected List <Subscription> mUris = new ArrayList <Subscription> ();
	protected FeedManager mFeedManager;
	protected BasicFeed mFeed;

	public AsyncFeedLoader (Context context, FeedManager manager) {
		super (context);
		// TODO Auto-generated constructor stub
		mFeedManager = manager;

		Log.d (this.getClass ().getSimpleName (), "new instance");
	}

	public void addFeed (Uri uri, boolean ignoreOld) {
		mUris.add (new Subscription (uri, ignoreOld));
	}

	public void addFeed (String path, boolean ignoreOld) {
		mUris.add (new Subscription (Uri.parse (FeedManager.API_BASE_URL + path),
				ignoreOld));
	}

	@Override
	public void onStartLoading () {

		if (mFeed != null) {
			deliverResult (mFeed);
		}
		else {
			forceLoad ();
		}
	}

	@Override
	public BasicFeed loadInBackground () {
		Log.d (this.getClass ().getSimpleName (), "loading in background...");
		mFeed = new BasicFeed (mFeedManager);

		for (Subscription s : mUris) {
			try {
				mFeed.fetch (s.uri, s.ignoreOld);
			}
			catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
			catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
		}
		Log.d (this.getClass ().getSimpleName (), "done loading in backgroud...");

		return mFeed;
	}

}
